<template>
  <div>
    <el-dialog
      title="预定餐点"
      class="gl_dialog_TitleLine"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :before-close="close"
      :show-close="false"
      width="592px"
    >
      <div class="dialog_form">
        <el-form ref="form" class="gl_form_mini" :model="updateForm" :rules="form_rules" label-position="top">
          <el-form-item prop="reserveStartDate" label="预定天数">
            <el-input v-show="false" v-model.trim="updateForm.reserveStartDate" />
            <el-date-picker
              v-model="orderTime"
              type="daterange"
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 433px;"
              :picker-options="pickerOptions"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="handleOrderTime"
            />
            <span v-if="updateForm.reserveStartDate" class="gl_pl_10">共{{ dayCount }}天</span>
          </el-form-item>
          <el-form-item prop="receptionName" label="预定人姓名">
            <el-input v-model="updateForm.receptionName" style="width: 307px" clearable placeholder="请输入预定人姓名" />
          </el-form-item>
          <el-form-item prop="receptionPhoneNumber" label="预定人电话号码">
            <el-input v-model="updateForm.receptionPhoneNumber" style="width: 307px" clearable placeholder="请输入预定人电话号码" />
          </el-form-item>
          <el-form-item prop="reserveNumber" label="预定份数">
            <el-input-number v-model="updateForm.reserveNumber" :min="1" size="small" />
          </el-form-item>
          <el-form-item prop="remark" label="备注">
            <el-input v-model="updateForm.remark" type="textarea" style="width: 503px" />
          </el-form-item>
        </el-form>
      </div>
      <el-row type="flex" justify="center">
        <el-col align="center">
          <el-button size="mini" style="border-radius: 8px;" @click="close()">取消</el-button>
          <el-button type="primary" :loading="loading" style="border-radius: 8px;" size="mini" @click="submit('form')">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import validator from '@/lib/validate/index.js';
import {
  api_POST_EventsManagementCateringEntryCateringEntry, // 预定
  api_PUT_EventsManagementCateringEntryCateringEntryCateringEntryId // 修改
} from '@/extend/api/gameswaggerApi/app';
import {
  SiSTKWEventsManagementCateringEntryInput,
  SiSTKWEventsManagementUpdateCateringEntryInput
} from '@/lib/form/game/swaggerForm';
import { CopyData } from '@/lib';
export default {
  name: 'FoodOrder',
  data() {
    return {
      dialogVisible: false,
      loading: false,
      createForm: new SiSTKWEventsManagementCateringEntryInput(),
      updateForm: new SiSTKWEventsManagementUpdateCateringEntryInput(),
      food: {}, // 预订的餐饮数据
      code: '', // 预定 or 编辑
      entryId: '', // 预定时为后勤报名总表Id, 编辑为row.id
      time: {}, // 后勤设置的餐饮预定时间
      pickerOptions: { // 时间范围限制
        disabledDate: time => {
          var sDate = '';
          var nowDay = new Date();
          nowDay.setTime(nowDay.getTime() - 24 * 60 * 60 * 1000);
          var startDate = this.time.startDateTime.split('T')[0];
          var startDay = new Date(startDate);
          if (nowDay > startDay) {
            sDate = nowDay;
          } else {
            var staDate = startDate.split('-');
            sDate = new Date(staDate[0], staDate[1] - 1, staDate[2]);
          }
          var endDate = this.time.endDateTime.split('T')[0];
          var enDate = endDate.split('-');
          var eDate = new Date(enDate[0], enDate[1] - 1, enDate[2]);
          return time.getTime() < sDate || time.getTime() > eDate;
        }
      },
      orderTime: [],
      dayCount: 0, // 总天数
      form_rules: {
        reserveStartDate: [validator.required('预定天数不能为空')],
        receptionName: [validator.required('预定人姓名不能为空')],
        receptionPhoneNumber: [
          validator.required('预定人电话号码不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkPhone(value, '电话号码格式错误'));
            },
            trigger: 'blur'
          }
        ],
        reserveNumber: [validator.required('预定份数不能为空')]
      }
    };
  },
  methods: {
    open(food, code, id, time) {
      this.dialogVisible = true;
      this.food = food;
      this.code = code;
      this.time = time;
      if (code === 'order') {
        this.entryId = id;
        this.updateForm.reserveNumber = this.updateForm.reserveNumber || 1;
      }
      if (code === 'edit') {
        this.entryId = id;
        this.orderTime = [food.reserveStartDate, food.reserveEndDate];
        const day = new Date(food.reserveEndDate).getTime() - new Date(food.reserveStartDate).getTime();
        this.dayCount = Math.floor(day / 86400000) + 1;
        CopyData(food, this.updateForm);
      }
    },
    // 处理预定天数
    handleOrderTime() {
      this.updateForm.reserveStartDate = this.orderTime && this.orderTime[0];
      this.updateForm.reserveEndDate = this.orderTime && this.orderTime[1];
      const day = new Date(this.updateForm.reserveEndDate).getTime() - new Date(this.updateForm.reserveStartDate).getTime();
      this.dayCount = Math.floor(day / 86400000) + 1;
    },
    close() {
      this.orderTime = [];
      this.updateForm = new SiSTKWEventsManagementUpdateCateringEntryInput();
      this.$refs['form'].resetFields();
      this.dialogVisible = false;
    },
    submit() {
      var that = this;
      that.loading = true;
      that.$refs['form'].validate(valid => {
        if (valid) {
          if (that.code === 'order') {
            CopyData(that.updateForm, that.createForm);
            that.createForm.logisticEntryId = that.entryId;
            that.createForm.competitionId = that.$route.query.id;
            that.createForm.launchedFoodId = that.food.id;
            api_POST_EventsManagementCateringEntryCateringEntry(that.createForm).then(res => {
              that.loading = false;
              if (res) {
                that.$message({ type: 'success', message: '预定成功！' });
                that.$parent.getOrderData();
              }
              that.close();
            }, (error) => {
              that.loading = false;
              that.$message({ type: 'error', message: error.error.message || '预定餐饮失败！' });
            });
          } else {
            api_PUT_EventsManagementCateringEntryCateringEntryCateringEntryId(that.entryId, that.updateForm).then(res => {
              that.loading = false;
              if (res) {
                that.$message({ type: 'success', message: '修改成功！' });
                that.$parent.getOrderData();
              }
              that.close();
            }, (error) => {
              that.loading = false;
              that.$message({ type: 'error', message: error.error.message || '修改失败！' });
            });
          }
        } else {
          that.loading = false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog_form {
  padding: -9px 30px -20px 18px;
}
.popover {
  background: rgba(254,204,204,0.50);
  color: #8d8d8d;
  padding: 3px 5px;
  position: relative;
}
.popover:after{
  content: '';
  position:absolute;
  right: 100%;
  bottom: 5px;
  width: 0;
  height :0;
  border: 6px solid transparent;
  border-right-width: 8px;
  border-right-color: rgba(254,204,204,0.50);;
}
</style>
